package com.marvels.common.interceptor;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import com.alibaba.fastjson.JSONObject;
import com.marvels.approve.common.utils.ApplicationContextAchieve;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.dao.UserRechargeLogDao;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.dto.UserDTO;
import com.marvels.common.dto.UserRechargeLogDTO;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.yeepay.shade.org.apache.commons.lang3.StringUtils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;

public class ReturnHandler extends RequestResponseBodyMethodProcessor {
	
	private UserRechargeLogDao userRechargeLogDao;
	
	public ReturnHandler(List<HttpMessageConverter<?>> converters) {
        super(converters);
    }
 
    /**
     * 该处理程序是否支持给定的方法返回类型(只有返回true才回去调用handleReturnValue)
     */
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
    	return (AnnotationUtils.findAnnotation(returnType.getContainingClass(), ResponseBody.class) != null ||
                returnType.getMethodAnnotation(ResponseBody.class) != null);
    }
 
    /**
     * 处理给定的返回值
     * 通过向 ModelAndViewContainer 添加属性和设置视图或者
     * 通过调用 ModelAndViewContainer.setRequestHandled(true) 来标识响应已经被直接处理(不再调用视图解析器)
     */
    @Override
    public void handleReturnValue(Object o, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws IOException, HttpMediaTypeNotAcceptableException {
        /**
         * 标识请求是否已经在该方法内完成处理
         */
        modelAndViewContainer.setRequestHandled(true);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        //获取开始时间
        Object startTimerObj = request.getAttribute(MarvelsCommonInterceptor.requestName);
        // 有值说明是需要处理的请求
        try {
        	if(startTimerObj != null){
        		UserDTO user = CacheUtils.getCacheUser();
    			//当前用户不是super
    			if(user != null && !isAdministrator(user.getUserCode())){
    				//其他用户
            		ApplicationContext applicationContext = ApplicationContextAchieve.getApplicationContext();
            		userRechargeLogDao = applicationContext.getBean(UserRechargeLogDao.class);
            		UserRechargeLogDTO userRechargeLogDTO = userRechargeLogDao.selectUserRechargeLog();
            		if(userRechargeLogDTO.getOperationState() != null || userRechargeLogDTO.getUsageState() != null){
            			MarvelsResultDTO result = null;
                		StringBuffer msg = new StringBuffer();
                		msg.append("尊敬的VIP客户，您好！当前您的账户已欠费 ");
                		msg.append(userRechargeLogDTO.getPresentArrears());
                		msg.append(" 元，请尽快充值。为避免系统服务停止，请于 ");
                		msg.append(userRechargeLogDTO.getLastDate() == null ? null : DateUtil.formatChineseDate(userRechargeLogDTO.getLastDate(), false));
                		msg.append(" 之前完成充值。");
                		// 使用受限
                		if(userRechargeLogDTO.getUsageState() == 1){
                			result = MarvelsResultDTO.getResult("0001", msg.toString(), null);
                		}else if(userRechargeLogDTO.getOperationState() == 1){
                			// 操作受限
                			result = MarvelsResultDTO.getResult("0000", msg.toString(), null);
                		}
                		// 加入系统停用json部分
                		if(result != null){
                			if(JSONUtil.isJsonObj(JSONObject.toJSONString(o))){
                				JSONObject json = (o == null) ? new JSONObject() : JSONObject.parseObject(JSONObject.toJSONString(o));
                    			json.put("systemDown", result);
                    			o = json;
                    			MarvelsLogUtil.getInstance().info(String.format("请求url：%s ，当前登录用户： %s ；系统停用，请求已被拦截",request.getRequestURL().toString(), user.getUserCode()));
                			}
                		}
            		}
    			}
            }
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(String.format("请求url：%s handleReturnValue 处理异常",request.getRequestURL().toString()), e);
		}
        super.handleReturnValue(o,methodParameter,modelAndViewContainer,nativeWebRequest);
    }
    
    private boolean isAdministrator(String userCode){
		if(StringUtils.equals(userCode, MarvelsConstant.SYSTEM_SUPER_CODE)){
			return true;
		}else{
			return false;
		}
	}
}
